package com.weayer.service.Impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.TimeoutUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @description: 实现锁续期
 *      创建一个类，确保 @EnableAsync 异步注解生效，异步执行的代码通过Spring容器注入
 * @author: Weayer
 **/
@Service
public class RenewRedisLock {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    // 异步加锁
    @Async
    public void renewRedisLock(String key, String value, int timePeriod){
        System.out.println("异步执行：锁续期");
        String s = stringRedisTemplate.opsForValue().get(key);
        // 存在 key-value，异步加锁
        if(StringUtils.isNotBlank(s) && s.equals(value)){
            // 休眠 timePeriod / 3，续期一次
            int renewPeriod = timePeriod / 3;
            try {
                TimeUnit.SECONDS.sleep(renewPeriod);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            stringRedisTemplate.expire(key, timePeriod, TimeUnit.SECONDS);
        }else{
            return;
        }
        renewRedisLock(key, value, timePeriod); // 递归调用
    }
}
